package com.itdlc.android.library.utils;

import android.os.Environment;
import android.os.StatFs;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;

public class SDCardUtil {
    public SDCardUtil() {
    }

    public static boolean isSDCardMounted() {
        return Environment.getExternalStorageState().equals("mounted");
    }

    public static String getSDCardBaseDir() {
        return isSDCardMounted() ? Environment.getExternalStorageDirectory().getAbsolutePath() : null;
    }

    public static long getSDCardSize() {
        if (isSDCardMounted()) {
            StatFs fs = new StatFs(getSDCardBaseDir());
            long count = fs.getBlockCountLong();
            long size = fs.getBlockSizeLong();
            return count * size / 1024L / 1024L;
        } else {
            return 0L;
        }
    }

    public static long getSDCardFreeSize() {
        if (isSDCardMounted()) {
            StatFs fs = new StatFs(getSDCardBaseDir());
            long count = fs.getFreeBlocksLong();
            long size = fs.getBlockSizeLong();
            return count * size / 1024L / 1024L;
        } else {
            return 0L;
        }
    }

    public static File createDir(String dirName) {
        File file = new File(getSDCardBaseDir() + File.separator + dirName);
        if (file.exists()) {
            return file;
        } else {
            file.mkdirs();
            return file;
        }
    }

    public static void saveToSDCard(String dirName, String fileName, String content) {
        File fileDir = createDir(dirName);
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }

        File file = new File(fileDir.getAbsolutePath() + "/" + fileName + ".txt");

        try {
            FileOutputStream fos = new FileOutputStream(file);
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos));
            writer.write(content);
            writer.flush();
            fos.close();
            writer.close();
        } catch (Exception var7) {
            var7.printStackTrace();
        }

    }

    public static String getFromSDCard(String dirName, String fileName) {
        String content = null;
        File file = new File(getSDCardBaseDir() + File.separator + dirName + "/" + fileName + ".txt");
        if (!file.exists()) {
            return null;
        } else {
            StringBuilder sb = new StringBuilder();

            try {
                BufferedReader reader = new BufferedReader(new FileReader(file));

                while((content = reader.readLine()) != null) {
                    sb.append(content);
                }

                reader.close();
            } catch (IOException var6) {
                var6.printStackTrace();
            }

            return sb.toString();
        }
    }
}
